package club.banyuan;

import club.banyuan.util.Constant;
import club.banyuan.util.PropUtil;
import com.alibaba.fastjson.JSONObject;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class EmployeeService {
    private int idCount = 1;
    private List<Employee> employeeList = new ArrayList<>();
    private static final EmployeeService INSTANCE = load();

    private EmployeeService() {
    }


    public int getIdCount() {
        return idCount;
    }

    public void setIdCount(int idCount) {
        this.idCount = idCount;
    }

    public List<Employee> getEmployeeList() {
        return employeeList;
    }

    public void setEmployeeList(List<Employee> employeeList) {
        this.employeeList = employeeList;
    }

    public static EmployeeService getINSTANCE() {
        return INSTANCE;
    }

    public void addEmployee(Employee employee) {
        Optional<Employee> any = employeeList.stream().filter(t -> t.getId()==employee.getId())
                .findAny();

        if (any.isPresent()) {
            throw new BadRequestException("员工已存在");
        }

        idCount++;
        employeeList.add(employee);
        save();
    }

    public void deleteEmployee(int id) {
        employeeList.removeIf(employee -> employee.getId() == id);
        save();
    }

    public Employee getEmployee(int id) {
        for (Employee employee : employeeList) {
            if (employee.getId() == id) {
                return employee;
            }
        }
        throw new BadRequestException("员工不存在 id:" + id);
    }

    public void updateEmployee(Employee employee) {
        Employee old = getEmployee(employee.getId());
        old.setId(employee.getId());
        old.setName(employee.getName());
        old.setSex(employee.getSex());
        old.setPhone(employee.getPhone());
        old.setEmail(employee.getEmail());
        old.setAddress(employee.getAddress());
        old.setEducation(employee.getEducation());
        old.setBirthday(employee.getBirthday());
        old.setDepartmentId(employee.getDepartmentId());
        old.setDepartmentName(employee.getDepartmentName(employee.getDepartmentId()));
        old.setPositionId(employee.getPositionId());
        old.setPositionName(employee.getPositionName(employee.getPositionId()));
        save();
    }

    private void save() {
        String rlt = JSONObject.toJSONString(this);
        try (FileOutputStream fileOutputStream = new FileOutputStream(
                PropUtil.getProp(Constant.Prop.EMPLOYEE_STORE))) {
            fileOutputStream.write(rlt.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static EmployeeService load() {
        try (FileInputStream inputStream = new FileInputStream(PropUtil.getProp(Constant.Prop.EMPLOYEE_STORE))) {

            return JSONObject.parseObject(inputStream, StandardCharsets.UTF_8, EmployeeService.class);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return new EmployeeService();
    }

    //查询字段
    //可选字段: String id, String name, String departmentName, String positionName, String sex,
    //必传字段: int page, int rows
    public List<Employee> getRowsList(int page, int rows, String id,
                                  String name, String departmentName, String positionName, String sex) {

        List<Employee> searchList = new ArrayList<>(getEmployeeList());

        //根据条件,检索符合要求的员工
        if (id != null && id.length() != 0) {
            searchList = searchList.stream().filter(t ->
                    (t.getId()+"").contains(id)).collect(Collectors.toList());
        }
        if (name != null && name.length() != 0) {
            searchList = searchList.stream().filter(t ->
                    t.getName().contains(name)).collect(Collectors.toList());
        }
        if (departmentName != null && departmentName.length() != 0) {
            searchList = searchList.stream().filter(t ->
                    t.getDepartmentName(t.getDepartmentId()).contains(departmentName)).collect(Collectors.toList());
        }
        if (positionName != null && positionName.length() != 0) {
            searchList = searchList.stream().filter(t ->
                    t.getPositionName(t.getPositionId()).contains(positionName)).collect(Collectors.toList());
        }
        if (sex != null && sex.length() != 0) {
            searchList = searchList.stream().filter(t ->
                    t.getSex().equals(sex)).collect(Collectors.toList());
        }

        int total = searchList.size();
        List<Employee> rowsList = new ArrayList<>();

        int allPages = (int) Math.ceil(total * 1.0 / rows);
        System.out.println(allPages);
        EmployeeService employeeService = HttpServer.getEmployeeService();
        if (allPages <= 1) {
            return searchList;
        }
        for (int i = 8 * (page - 1), j = 0; i < employeeService.getEmployeeList().size() && j < 8; i++, j++) {
            rowsList.add(employeeService.getEmployeeList().get(i));
        }
        return rowsList;
    }


    public static void main(String[] args) {
        EmployeeService employeeService = new EmployeeService();
        Employee employee = new Employee();
        employee.setId(100001);
        employee.setName("e1");
        employee.setSex("male");
        employee.setPhone("13812345678");
        employee.setEmail("133@163.com");
        employee.setAddress("address1");
        employee.setEducation("Master");
        employee.setBirthday("1999-10-10");
        employee.setDepartmentId(2);
        employee.setDepartmentName("研发部");
        employee.setPositionId(1);
        employee.setPositionName("员工");
        employeeService.addEmployee(employee);

        Employee employee2 = new Employee();
        employee2.setId(100002);
        employee2.setName("e2");
        employee2.setSex("male");
        employee2.setPhone("1581231231");
        employee2.setEmail("1343253@163.com");
        employee2.setAddress("address2");
        employee2.setEducation("Master");
        employee2.setBirthday("1995-1-10");
        employee2.setDepartmentId(1);
        employee2.setDepartmentName(employee2.getDepartmentName(1));
        employee2.setPositionId(2);
        employee2.setPositionName(employee2.getPositionName(2));
        employeeService.addEmployee(employee2);

        Employee employee3 = new Employee();
        employee3.setId(100006);
        employee3.setName("eam");
        employee3.setSex("female");
        employee3.setPhone("15189864030");
        employee3.setEmail("11323444473@163.com");
        employee3.setAddress("address3");
        employee3.setEducation("Master");
        employee3.setBirthday("1998-06-125");
        employee3.setDepartmentId(3);
        employee3.setDepartmentName(employee3.getDepartmentName(3));
        employee3.setPositionId(3);
        employee3.setPositionName(employee3.getPositionName(3));
        employeeService.addEmployee(employee3);

    }
}